import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

enum UiStateStatus { loading, failed, error, unlogin, complated }

class UiState extends StatefulWidget {
  const UiState({
    super.key,
    this.child,
    this.preview,
    this.previewDecoration,
    this.failed,
    this.error,
    this.errorBuider,
    this.controller,
    this.lazyLoad = true,
    this.initStatus = UiStateStatus.loading,
    this.loadingText = '正在加载',
    this.onLoad,
    this.onShow,
    this.onReady,
    this.onHide,
    this.onRouteDone,
    this.onUnload,
    this.onInactive,
    this.onPaused,
    this.onResumed,
    this.onDetached,
  });

  final bool lazyLoad;
  final Widget? child;
  final Widget? failed;
  final Widget? preview;
  final Widget? error;
  final BoxDecoration? previewDecoration;
  final UiStateController? controller;
  final UiStateStatus initStatus;
  final String loadingText;
  final Function(ResponseModel data)? errorBuider;

  /// 页面加载时触发
  final Function()? onLoad;

  /// 页面显示/切入前台时触发 isFirstShow：是否第一次触发
  final Function(bool isFirstShow)? onShow;

  /// 页面初次渲染完成时触发。一个页面只会调用一次，代表页面已经准备妥当，可以和视图层进行交互
  final Function()? onReady;

  /// 页面隐藏/切入后台时触发
  final Function()? onHide;

  /// 路由动画完成时触发
  final Function()? onRouteDone;

  /// 页面卸载时触发
  final Function()? onUnload;

  /// app失去焦点
  final Function()? onInactive;

  /// app从后台恢复到前台
  final Function()? onResumed;

  /// app进入后台
  final Function()? onPaused;

  /// app委派
  final Function()? onDetached;

  @override
  State<UiState> createState() => UiStateState();
}

class UiStateState extends State<UiState> with WidgetsBindingObserver {
  /// 页面状态
  late UiStateStatus status;

  /// 页面过渡动画是否完成
  bool pageAnimateCompleted = false;

  /// 数据类型
  ResponseModel data = ResponseModel();

  @override
  void initState() {
    /// 是否开启页面延迟
    pageAnimateCompleted = !widget.lazyLoad;

    /// 设置初始化状态
    setState(() {
      status = widget.initStatus;
    });

    /// 绑定控制器
    widget.controller?.bind(this);

    super.initState();
  }

  /// 更新值
  void setValue(Function() fn) {
    if (mounted) {
      setState(fn);
    }
  }

  @override
  Widget build(BuildContext context) {
    return UiLifeCycle(
      onRouteDone: () {
        if (!pageAnimateCompleted) {
          setState(() {
            pageAnimateCompleted = true;
          });
          widget.onRouteDone?.call();
        }
      },
      onLoad: widget.onLoad,
      onHide: widget.onHide,
      onShow: widget.onShow,
      onPaused: widget.onPaused,
      onResumed: widget.onResumed,
      onReady: widget.onReady,
      onDetached: widget.onDetached,
      onInactive: widget.onInactive,
      onUnload: widget.onUnload,
      child: AnimatedSwitcher(
        duration: kThemeAnimationDuration,
        child: pageAnimateCompleted ? currentView() : previewView(),
      ),
    );
  }

  // 获取当前视图
  Widget currentView() {
    Widget child;
    switch (status) {
      case UiStateStatus.loading:
        child = previewView();
        break;
      case UiStateStatus.failed:
        child = UiTap(
          onTap: () async {
            setState(() {
              status = UiStateStatus.loading;
            });
            await 0.1.delay();
            widget.onLoad?.call();
          },
          child: failedView(),
        );
        break;
      case UiStateStatus.unlogin:
        child = loginView();
        break;
      case UiStateStatus.error:
        child = LayoutBuilder(
          builder: (context, constraints) {
            return widget.errorBuider?.call(data) ??
                widget.error ??
                UiResult(
                  text: data.msg,
                );
          },
        );
        break;
      default:
        child = widget.child ?? Container();
    }
    return child;
  }

  /// 预览视图
  Widget previewView() {
    return widget.preview ??
        Container(
          decoration: widget.previewDecoration,
          height: MediaQuery.of(context).size.height * 0.8,
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.6),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: const CupertinoActivityIndicator(
                    color: Colors.white,
                    radius: 15,
                  ),
                ),
                //const CircularProgressIndicator(),
                // const SizedBox(height: 15),
                // Text(
                //   widget.loadingText,
                //   style: TextStyle(
                //     color: Colors.black54,
                //     fontSize: 13,
                //   ),
                // ),
              ],
            ),
          ),
        );
  }

  // 登录视图
  Widget loginView() {
    return UiTap(
      onTap: () async {
        var res = await AuthService.instance.isLoginOrToLogin();
        if (res) {
          widget.onLoad?.call();
        }
      },
      child: SizedBox(
        height: MediaQuery.of(context).size.height * 0.7,
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                'res/images/ikons/login.png',
                width: 200,
              ),
              const SizedBox(height: 10),
              const Text('请先登录', textScaler: TextScaler.linear(1.2)),
              const SizedBox(height: 10),
              const Text('轻触屏幕登录', textScaler: TextScaler.linear(0.9)),
            ],
          ),
        ),
      ),
    );
  }

  // 失败视图
  Widget failedView() {
    return widget.failed ??
        SizedBox(
          height: MediaQuery.of(context).size.height * 0.7,
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset('res/images/ikons/network.png', width: 180),
                const SizedBox(height: 10),
                const Text('网络连接失败！', textScaler: TextScaler.linear(1.2)),
                const SizedBox(height: 10),
                const Text(
                  '请检查网络后轻触屏幕重新尝试',
                  textScaler: TextScaler.linear(0.9),
                ),
              ],
            ),
          ),
        );
  }
}

class UiStateController {
  late UiStateState state;

  // 绑定
  bind(UiStateState pageState) {
    state = pageState;
  }

  startLoading() {
    state.setValue(() {
      state.status = UiStateStatus.loading;
    });
  }

  // 更新状态
  setStatus(ResponseModel data) {
    switch (data.code) {
      case 0:
        state.status = UiStateStatus.error;
        break;
      case 500:
        state.status = UiStateStatus.failed;
        break;
      case 10001:
        state.status = UiStateStatus.unlogin;
        break;
      default:
        state.status = UiStateStatus.complated;
    }
    state.setValue(() {
      state.status;
      state.data = data;
    });
  }
}
